package com.kaifamiao.tracking.rewrite;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/counter/*")
public class CounterServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();

        if( session.isNew() ) {
            String uri = request.getRequestURI();
            String qs = request.getQueryString();
            uri = uri + ( qs == null ? "" : ("?"+qs) );
            System.out.printf("url: %s \n" , uri );
            // String encoded = response.encodeURL( uri );
            String encoded = response.encodeRedirectURL( uri );
            System.out.printf("encoded url: %s \n" , encoded );
            response.sendRedirect( encoded );
            return;
        }

        // 尝试从会话对象中获得名称是 counter 的属性值
        Integer count = (Integer)session.getAttribute( "counter" );
        // 若 count 为 null 则表示 counter 属性不存在
        if( count == null ){
            count = 0;
        }
        // 将 count 增加 一 后重新添加到 会话对象 的属性中
        session.setAttribute( "counter", ++count );

        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );
        PrintWriter out = response.getWriter();

        out.println( "<h1 style='text-align: center'>" );
        out.println( count );
        out.println( "</h1>" );

    }

}
